package com.lxy.cxcyxmmsbackend.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxy.cxcyxmmsbackend.sys.entity.QxglUser;
import com.lxy.cxcyxmmsbackend.sys.exceptionHandle.exce.NormalException;
import com.lxy.cxcyxmmsbackend.sys.req.LoginReq;
import com.lxy.cxcyxmmsbackend.sys.req.PageReq;
import com.lxy.cxcyxmmsbackend.sys.req.ResetPwdReq;
import com.lxy.cxcyxmmsbackend.sys.res.Result;
import com.lxy.cxcyxmmsbackend.sys.service.QxglUserService;
import com.lxy.cxcyxmmsbackend.sys.utils.JwtUtil;
import com.lxy.cxcyxmmsbackend.sys.utils.UpPhotoNameUtils;
import com.sun.corba.se.impl.corba.EnvironmentImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 用户管理
 * @author 刘新颖
 * @since 2024-01-07
 */
@Api(tags = "权限管理_用户")
@RestController
@RequestMapping("/qxglUser")
public class QxglUserController {

    @Resource
    QxglUserService qxglUserService;

    @Autowired
    Environment environment;

    @ApiOperation("登录")
    @RequestMapping("login")
    public Result login(@RequestBody LoginReq loginReq) {
        return qxglUserService.login(loginReq);
    }

    @ApiOperation("分页模糊查询")
    @RequestMapping("selectUserPage")
    public Result selectUserPage(@RequestBody PageReq pageReq) {
        return qxglUserService.selectUserPage(pageReq);
    }

    @ApiOperation("查询角色id 权限id apis")
    @RequestMapping("selectIds")
    public Result selectIds(@RequestHeader("token") String token) {
        String userBh = JwtUtil.getUserName(token);
        return qxglUserService.selectIds(userBh);
    }

    @ApiOperation("新增用户")
    @RequestMapping("insertUser")
    public Result insertUser(@RequestBody QxglUser qxglUser) {
        qxglUser.setAvatarUrl("default.jpg");
        return qxglUserService.insertUser(qxglUser);
    }
    @ApiOperation("修改用户信息")
    @RequestMapping("updateUser")
    public Result updateUser(@RequestBody QxglUser qxglUser) {
        boolean b = qxglUserService.updateById(qxglUser);
        if (!b){
            throw new NormalException("修改用户信息失败！");
        }
        return Result.success("修改用户信息成功！",qxglUser);
    }

    @ApiOperation("修改密码")
    @RequestMapping("resetPwd")
    public Result resetPwd(@RequestBody ResetPwdReq resetPwdReq) {
        QxglUser user = qxglUserService.getById(resetPwdReq.getUserBh());
        if (user == null){
            throw new NormalException("不存在该用户");
        }
        //校验密码
        if (resetPwdReq.getPassword().equals(user.getUserMm())){
            user.setUserMm(resetPwdReq.getNewPass());
            boolean b = qxglUserService.updateById(user);
            if (!b){
                throw new NormalException("修改密码失败！");
            }
        }
        return Result.success("修改密码成功！",user);
    }

    @ApiOperation("删除用户")
    @RequestMapping("deleteUser/{userBh}")
    public Result deleteUser(@PathVariable("userBh") String userBh) {
        QxglUser qxglUser = qxglUserService.getById(userBh);
        qxglUser.setStatus("-1");
        boolean b = qxglUserService.updateById(qxglUser);
        if (!b){
            throw new NormalException("停用用户失败！");
        }
        return Result.success("停用用户成功！",qxglUser);
    }

    @ApiOperation("获取用户详情")
    @RequestMapping("getUserDetail/{userBh}")
    public Result getUserDetail(@PathVariable("userBh") String userBh) {
        QxglUser user = qxglUserService.getById(userBh);
        if (user == null){
            throw new NormalException("不存在该用户");
        }
        return Result.success("查询用户详情成功",user);
    }


    @ApiOperation("上传头像")
    @RequestMapping("uploadTX")
    public String  uploadTX(@RequestParam("file") MultipartFile file, HttpServletRequest request, String userCode) {
        QueryWrapper<QxglUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(QxglUser::getUserCode,userCode);
        QxglUser user = qxglUserService.getOne(wrapper);

        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            String url = environment.getProperty("front-assert-url.avatar");
            Path path = Paths.get( url+ fileName);
            Files.write(path, bytes);//写入文件
            String avatar_url=fileName;
            if (user.getStatus().equals("1")){//判断学生状态调用dao层方法，把图片名称写入数据库
                user.setAvatarUrl(avatar_url);
                boolean b = qxglUserService.updateById(user);
            }
            System.out.println(fileName+"\n");
            return fileName;//返回文件名字
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}

